package com.whq.thrift.api.web.admin.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;

import com.whq.thrift.api.web.admin.util.LoginUtil;

/**
 * 记录请求信息Filter
 * 
 * @author wanghuaiqiang
 * 
 */
public class SaveAccessInfoFilter implements Filter {
	private Logger logger = LoggerFactory.getLogger("logger_access");
	private WebApplicationContext ctx;

	public void init(FilterConfig filterConfig) throws ServletException {
		ServletContext servletContext = filterConfig.getServletContext();
		Object ob = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		ctx = (WebApplicationContext) ob;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
//		HttpServletResponse resp = (HttpServletResponse) response;
		
		Map<String, String> mapParams = new HashMap<String, String>(0);
		Enumeration<String> paramNames = request.getParameterNames(); 
		while(paramNames.hasMoreElements()){  
	        String paramName = (String)paramNames.nextElement();  
	        String[] paramValues = request.getParameterValues(paramName);  
	        if(paramValues.length == 1){  
	            String paramValue = paramValues[0];  
	            if(paramValue.length() != 0){  
	            	mapParams.put(paramName, paramValue);
	            }  
	        }  
	    }  
		
		
		String loginTicket = LoginUtil.getLoginTicket(req);
		logger.debug(loginTicket + " request: " + req.getRequestURI() + ", params: [" + mapParams + "]");
		
		chain.doFilter(request, response);
	}

	public void destroy() {

	}

}
